package com.gin.kotlin.no_gay_alliance.fragment.main.me.follow

import com.gin.kotlin.no_gay_alliance.adapter.follow.FollowDynamicsAdapter
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingFragment
import com.gin.kotlin.no_gay_alliance.base.RecyclerViewScrollListener
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.databinding.FragmentMainMeFollowDynamicsBinding
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.FollowDynamicsProvider
import com.gin.nga.response.follow.FollowStatusData

/**
 * 关注动态
 */
class FollowDynamicsFragment: AbstractBindingFragment<FragmentMainMeFollowDynamicsBinding>(), RCallback<FollowStatusData, Int> {
    private lateinit var adapter: FollowDynamicsAdapter
    private var page = 1
    private var hasNext = true
    private var userId = 0L

    override fun onCreateView() {
        val b = this.b ?: return

        this.adapter = FollowDynamicsAdapter(requireContext(),handler!!)
        b.recyclerView.adapter = adapter
        b.swipeRefreshLayout.setOnRefreshListener { refresh() }
        b.recyclerView.addOnScrollListener(RecyclerViewScrollListener(scrollToBottomListener = object : RecyclerViewScrollListener.ScrollToBottomListener {
            override fun onScrollToBottom() {
                if (hasNext) {
                    page++
                    toast("正在加载...")
                    request(true)
                } else {
                    toast("没有更多了...")
                }
            }
        }))
        request()
    }

    override fun onResume() {
        super.onResume()
        if (userId != App.INSTANCE.account.userId) refresh()
    }

    /**
     * 刷新
     */
    private fun refresh() {
        adapter.clear()
        page = 1
        hasNext = true
        request(true)
    }

    private fun request(ignoreCache: Boolean = false) {
        val b = this.b ?: return
        b.swipeRefreshLayout.isRefreshing = true
        this.userId = App.INSTANCE.account.userId

        FollowDynamicsProvider.getInstance().enqueue(
            params = page,
            ignoreCache = ignoreCache,
            callback = this
        )
    }

    override fun onSuccess(data: FollowStatusData, ignoreCache: Boolean) {
        val b = this.b ?: return
        b.swipeRefreshLayout.isRefreshing = false

        val list = data.data

        adapter.pushData(list)

        if (list.isNullOrEmpty()) hasNext = false
    }

    override fun onError(errorMessage: String) {
        toastLong(errorMessage)
    }

}